﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using MySql.Data.MySqlClient;

namespace FMixPlayer
{
    public partial class FormShowTask : Form
    {
        Task CurrentTask;
        FormMain ParentForm;

        bool isNewTask=false;

        public FormShowTask(FormMain _parentForm)//
        {
            InitializeComponent();
            ParentForm = _parentForm;
            //
            isNewTask = true;
            CurrentTask = new Task();
            FillUsers();

            FillStatuses();
            labelTextCreator.Text = FormMain.CurrentUser;
        }

        public FormShowTask(FormMain _parentForm, Task inputTask)
        {
            InitializeComponent();
            ParentForm = _parentForm;

            //
            CurrentTask = inputTask;

            FillUsers();
            FillStatuses();

            //
            textBoxName.Text = inputTask.name;
            labelTextCreator.Text = inputTask.creator;
            richTextBoxComment.Text = inputTask.comment;
            numetricCompleted.Value = inputTask.completed;
            dateStartTime.Value = Convert.ToDateTime(inputTask.starttime);
            dateEndTime.Value = Convert.ToDateTime(inputTask.endtime);
            if (FormMain.CurrentUser != inputTask.creator)
            {
                textBoxName.Enabled = false;

                dateStartTime.Enabled = false;
                dateEndTime.Enabled = false;
                comboBoxUsers.Enabled = false;
            }
        }

        void FillStatuses()//Заполнение комбобокса статусами
        {
            for (int i = 0; i <= FormMain.Statuses.Count - 1; i++)
            {
                comboBoxStatus.Items.Add(FormMain.Statuses[i].status);
                if (FormMain.Statuses[i].status == CurrentTask.status) comboBoxStatus.SelectedIndex = i;
            }
        }

        void FillUsers()//Заполнение комбобокса пользователями
        {
            for(int i=0;i<=FormMain.Users.Count-1;i++){
                comboBoxUsers.Items.Add(FormMain.Users[i].login);
                if (FormMain.Users[i].login == CurrentTask.executor) comboBoxUsers.SelectedIndex = i;
            }
        }

        private void createCurrentTask()//Создать текущую задачу в БД
        {

            string SaveCommand = "INSERT INTO "+FormMain.currentProject+" (name, creator, executor,comment,starttime,endtime,completed,status,temp) VALUES (" + 
                "'" + textBoxName.Text + "'," +
               "'" + labelTextCreator.Text + "'," +
               "'" + comboBoxUsers.Text + "'," +
               "'" + richTextBoxComment.Text + "'," +
               "'" + dateStartTime.Value.ToString("yyyy:MM:dd HH:mm:ss") + "'," +
               "'" + dateEndTime.Value.ToString("yyyy:MM:dd HH:mm:ss") + "'," +
               "'" + Convert.ToInt16(numetricCompleted.Value) + "'," +
               "'" + comboBoxStatus.Text + "'," +
               "'null'" +
               ")";


            MySqlCommand AddTask = new MySqlCommand(SaveCommand, FormMain.globalConnection);

            AddTask.ExecuteScalar();
            //После этого обновляем данные на главной форме
            ParentForm.updateAll();
        }


        private void saveCurrentTask()//Сохранить изменения в БД
        {
            string SaveCommand = "UPDATE "+FormMain.currentProject+" SET name='"+textBoxName.Text+
                "', executor='" + comboBoxUsers.Text +
                "', comment='" + richTextBoxComment.Text +
                "', starttime='" + dateStartTime.Value.ToString("yyyy:MM:dd HH:mm:ss") +
                "', endtime='" + dateEndTime.Value.ToString("yyyy:MM:dd HH:mm:ss") +
                "', completed='" + numetricCompleted.Value +
                "', status='" + comboBoxStatus.Text +
                "' WHERE id=" + CurrentTask.id.ToString();
            

            MySqlCommand AddTask = new MySqlCommand(SaveCommand, FormMain.globalConnection);
 
            AddTask.ExecuteScalar();
            ParentForm.updateAll();


        }

        private void Save()
        {

            //сохранить задачу
            if (isNewTask == true)
            {
                //создаем новую в БД
                createCurrentTask();
            }
            else
            {
                //либо изменяем существующую
                saveCurrentTask();
            }
            //после создания задача уже не являеся новой
            isNewTask = false;
        }
        private void buttonSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void labelTextCreator_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Save();
            this.Hide();
        }

        private void comboBoxStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxStatus.Text == "Выполнено") numetricCompleted.Value = 100;
        }
    }
}
